package com.zgc.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class JsonUtil {

    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    private final static ObjectMapper mapper = new ObjectMapper();

    public static void Object2File(Object object, String filePath, String fileName) {
        try {
            File file = new File(getPath(filePath).getPath(), fileName);
            logger.debug("序列化路径[{}]", file);
            mapper.writeValue(file, object);
        } catch (IOException e) {
            logger.error("序列化失败", e);
        }
    }

    public static String objectToString(Object object) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            logger.error("序列化失败", e);
        }
        return null;
    }


    public static <T> T file2Object(Class<T> object, String filePath, String fileName) {
        try {
            File file = new File(getPath(filePath).getPath(), fileName);
            logger.debug("反序列化路径[{}]", file);
            return mapper.readValue(file, object);
        } catch (IOException e) {
            logger.error("反序列化失败", e);
        }
        return null;
    }


    private static URL getPath(String path) {
        return JsonUtil.class.getResource(path);
    }

}
